// pages/activity/list/list.js
const activityApi = require('../../../api/activity.js')
const util = require('../../../utils/util.js')

Page({
  data: {
    currentTab: 'all',
    searchKeyword: '',
    activities: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.loadActivities()
  },

  // 加载活动列表
  async loadActivities(refresh = false) {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const params = {
        page: refresh ? 1 : this.data.page,
        page_size: this.data.pageSize
      }
      
      if (this.data.currentTab !== 'all') {
        params.status = this.data.currentTab
      }
      
      if (this.data.searchKeyword) {
        params.keyword = this.data.searchKeyword
      }
      
      const res = await activityApi.getActivityList(params)
      
      if (res.code === 200) {
        const activities = refresh ? res.data.items : [...this.data.activities, ...res.data.items]
        
        this.setData({
          activities: activities,
          hasMore: res.data.has_more,
          page: refresh ? 2 : this.data.page + 1
        })
      }
    } catch (error) {
      console.error('加载活动列表失败:', error)
      util.showError('加载失败')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadActivities(true)
    wx.stopPullDownRefresh()
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    
    if (tab === this.data.currentTab) return
    
    this.setData({
      currentTab: tab,
      page: 1,
      hasMore: true,
      activities: []
    })
    
    this.loadActivities(true)
  },

  // 搜索输入
  onSearchInput: util.debounce(function(e) {
    this.setData({
      searchKeyword: e.detail.value,
      page: 1,
      hasMore: true,
      activities: []
    })
    
    this.loadActivities(true)
  }, 500),

  // 搜索确认
  onSearch() {
    this.setData({
      page: 1,
      hasMore: true,
      activities: []
    })
    
    this.loadActivities(true)
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadActivities()
    }
  },

  // 跳转到详情
  goToDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${id}`
    })
  },

  // 分享给好友/群聊
  onShareAppMessage() {
    return {
      title: '探索语言成长社 - 演讲活动列表',
      path: '/pages/activity/list/list',
      imageUrl: '/assets/images/activity01.jpg'
    }
  }
})

